<template>
  <div>
    <!-- 统计信息卡片 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>总订单数</span>
            </div>
          </template>
          <div class="text item">{{ orderStats.totalOrders || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>总金额</span>
            </div>
          </template>
          <div class="text item">¥{{ orderStats.totalAmount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>待处理订单</span>
            </div>
          </template>
          <div class="text item">{{ orderStats.pendingOrders || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>已完成订单</span>
            </div>
          </template>
          <div class="text item">{{ orderStats.completedOrders || 0 }}</div>
        </el-card>
      </el-col>
    </el-row>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" @keyup.enter="onSubmit">
        <el-form-item label="订单编号" prop="order_no">
          <el-input v-model="searchInfo.order_no" placeholder="订单编号模糊查询" />
        </el-form-item>
        <el-form-item label="订单状态" prop="order_status">
          <el-select v-model="searchInfo.order_status" clearable placeholder="请选择">
            <el-option label="待支付" :value="1" />
            <el-option label="待发货" :value="2" />
            <el-option label="已发货" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已取消" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button type="success" icon="refresh" @click="getOrderStats">刷新统计</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="订单编号111" prop="order_no" width="150" />
        <el-table-column align="left" label="商品名称" prop="product_name" width="150" />
        <el-table-column align="left" label="付款额" prop="price" width="120">
          <template #default="scope">
            <span>¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="订单状态" prop="order_status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.order_status)">{{ getStatusText(scope.row.order_status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="下单用户" prop="nickname" width="120" />
        <el-table-column align="left" label="下单时间" prop="created_at" width="180">
          <template #default="scope">
            <span>{{ formatDate(scope.row.created_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="查看更多" fixed="right" min-width="240">
          <template #default="scope">
            <el-button type="primary" link icon="detail" class="table-button" @click="orderDetailFunc(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>


  </div>
</template>

<script setup>
import {
  createOrder,
  deleteOrder,
  updateOrder,
  findOrder,
  getOrderList,
  updateOrderStatus,
  getOrderStats
} from '@/api/order'
import { formatTimeToStr } from '@/utils/date'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

defineOptions({
  name: 'Order'
})

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  order_no: '',
  product_name: '',
  price: 0,
  order_status: 1,
  nickname: '',
  desc: '',
  created_at: 0,
})

// 验证规则
const rule = reactive({
  order_no: [{
    required: true,
    message: '请输入订单编号',
    trigger: 'blur'
  }],
  product_name: [{
    required: true,
    message: '请输入商品名称',
    trigger: 'blur'
  }],
  price: [{
    required: true,
    message: '请输入付款额',
    trigger: 'blur'
  }],
  order_status: [{
    required: true,
    message: '请选择订单状态',
    trigger: 'change'
  }],
  nickname: [{
    required: true,
    message: '请输入下单用户',
    trigger: 'blur'
  }]
})

const searchInfo = ref({})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const orderStats = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getOrderList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============
// 获取统计信息
const getOrderStatsFunc = async() => {
  const res = await getOrderStats()
  if (res.code === 0) {
    orderStats.value = res.data || {}
  }
}

getOrderStatsFunc()

// ============== 新增修改删除控制 =============

const type = ref('')
const dialogFormVisible = ref(false)

const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    order_no: '',
    product_name: '',
    price: 0,
    order_status: 1,
    nickname: '',
    desc: '',
    created_at: 0
  }
}
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createOrder(formData.value)
        break
      case 'update':
        res = await updateOrder(formData.value)
        break
      default:
        res = await createOrder(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
      getOrderStatsFunc()
    }
  })
}

const router = useRouter()

const orderDetailFunc = async(row) => {
  // 跳转到订单详情页
  router.push({
    name: 'orderDetail', 
    query: { order_no: row.order_no }
  })
}

const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrderFunc(row)
  })
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const getOneDetail = async(row) => {
  const res = await findOrder({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.order
    dialogFormVisible.value = true
  }
}

const deleteOrderFunc = async(row) => {
  const res = await deleteOrder({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
    getOrderStatsFunc()
  }
}

// 更新订单状态
const updateStatus = async(row, status) => {
  const res = await updateOrderStatus({ ID: row.ID, Status: status })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '状态更新成功'
    })
    getTableData()
    getOrderStatsFunc()
  }
}

// 辅助函数
const formatDate = (time) => {
  if (time && time > 0) {
    // 如果是Unix时间戳，转换为毫秒
    const timestamp = time.toString().length === 10 ? time * 1000 : time
    return formatTimeToStr(new Date(timestamp), 'yyyy-MM-dd hh:mm:ss')
  } else {
    return ''
  }
}

const getStatusType = (status) => {
  const statusMap = {
    1: 'info',
    2: 'warning',
    3: 'warning',
    4: 'success',
    5: 'danger'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    1: '待支付',
    2: '待发货',
    3: '已发货',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || status
}
</script>

<style scoped>
.text {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.item {
  margin-bottom: 18px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 100%;
}
</style>